﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Hrunga.PVCM.Framework.Attributes;

namespace Hrunga.PVCM.Framework.Helpers
{
    /// <summary>
    /// Helper class to initialize a form with attributes
    /// </summary>
    public static class ViewInitializer
    {
        /// <summary>
        /// Initializes the view by attributes.
        /// </summary>
        /// <param name="view">The view.</param>
        public static void InitializeByAttributes(IView view)
        {
            MemberInfo info = view.GetType();
            object[] attributes = info.GetCustomAttributes(typeof(FormAttribute), true);
            if (attributes.Length == 1)
            {
                var attribute = (FormAttribute)attributes[0];
                Type presenterType = attribute.Presenter;
                Type viewType = attribute.View;

                Type[] typeArgs = { presenterType, viewType };
                Type constructedViewWrapper = typeof(ViewWrapper<,>).MakeGenericType(typeArgs);
                Activator.CreateInstance(constructedViewWrapper, view);
            }
            else if (attributes.Length == 0)
            {
                throw new ApplicationException("No Form Attributes are set.");
            }
            else
            {
                throw new ApplicationException("Only one Form Attributes can be set.");
            }
        }
    }
}
